package 锁;

import java.util.concurrent.CountDownLatch;

/**
 * @Author zhang lei
 * @Date 2021-10-28 16:13
 */
public class CountDownLatchTest {
    public static void main(String[] args) {
        CountDownLatch c = new CountDownLatch(2);
        WorkX workx = new WorkX(c);
        WorkY worky = new WorkY(c);

        new Thread(workx, "1-test").start();
        new Thread(worky, "2-test").start();


    }

}

class WorkX implements Runnable{

    private CountDownLatch countDownLatch;

    public WorkX(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("进入线程X，当前数量为"+countDownLatch.getCount());

        countDownLatch.countDown();
        System.out.println("线程X，当前数量为"+countDownLatch.getCount());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            countDownLatch.await();
            System.out.println("线程XXXXX结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class WorkY implements Runnable{

    private CountDownLatch countDownLatch;

    public WorkY(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        System.out.println("进入线程Y，当前数量为"+countDownLatch.getCount());
        countDownLatch.countDown();

        System.out.println("线程Y，当前数量为"+countDownLatch.getCount());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            countDownLatch.await();
            System.out.println("线程XXXXX结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
